package ca.radiologydb.util;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;

/**
 * Original author Li-Yan Yuan
 * 
 * This servlet takes two parameters in its request, img_id and the size (type)
 * of image And outputs it
 * 
 * @author Nicholas Liu
 * 
 */
public class GetBigPic extends HttpServlet implements SingleThreadModel {

	/**
	 * This method receives an HTTP request for an image, with two parameters
	 * attached to request in the form ?type=param1&imgid=param2
	 * And returns the correct image specified by param1 (type/size),
	 * and param2 (imgid).
	 * 
	 * @param request		An object containing the request made of the servlet.
	 * @param response		An object containing the response provided by the servlet.
	 * @throws ServletException
	 * @throws IOException
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String type = request.getParameter("type");
		int imgid = Integer.parseInt(request.getParameter("imgid"));
		String query;

		query = "select " + type + " from pacs_images where image_id=" + imgid;

		ServletOutputStream out = response.getOutputStream();

		/*
		 * to execute the given query
		 */
		Connection conn = null;
		try {
			conn = getConnected();
			Statement stmt = conn.createStatement();
			ResultSet rset = stmt.executeQuery(query);

			if (rset.next()) {
				response.setContentType("image/jpg");
				InputStream input = rset.getBinaryStream(1);
				int imageByte;
				while ((imageByte = input.read()) != -1) {
					out.write(imageByte);
				}
				input.close();
			} else
				out.println("no picture available");
		} catch (Exception ex) {
			out.println(ex.getMessage());
		}
		// to close the connection
		finally {
			try {
				conn.close();
			} catch (SQLException ex) {
				out.println(ex.getMessage());
			}
		}
	}

	
	/**
	 * Connects the servlet to the database and returns the connection object.
	 * 
	 * @return				A connection object needed for database operations.
	 * @throws Exception
	 */
	private Connection getConnected() throws Exception {

		String username = "njliu";
		String password = "s1llyfox";
		String drivername = "oracle.jdbc.driver.OracleDriver";
		String dbstring = "jdbc:oracle:thin:@gwynne.cs.ualberta.ca:1521:CRS";

		/*
		 * to connect to the database
		 */
		Class drvClass = Class.forName(drivername);
		DriverManager.registerDriver((Driver) drvClass.newInstance());
		return (DriverManager.getConnection(dbstring, username, password));
	}
}
